package com.liudadan.dao.impl;

import com.liudadan.dao.StudentDao;
import com.liudadan.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private DataSource dataSource;
    @Override
    public List<Student> findAllStudents() throws SQLException {
        Connection connection = dataSource.getConnection();
        String sql = "select id,name,gender,age from studb.students";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Student> list = new ArrayList<>();
        while(resultSet.next()){
            Student student = new Student();
            student.setId(resultSet.getInt("id"));
            student.setName(resultSet.getString("name"));
            student.setGender(resultSet.getString("gender"));
            student.setAge(resultSet.getInt("age"));
            list.add(student);
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
        return list;
    }
}
